package com.lxn.web.controller;

import com.lxn.hrm.util.AjaxResult;
import com.lxn.utils.FastDfsApiOpr;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/fastdfs")
public class FastdfsController {
    //文件上传
    @RequestMapping("/uploadBytes")
    public AjaxResult uploadBytes(@RequestBody byte[] file, @RequestParam("extName")String extName){
        try {
            String filePath = FastDfsApiOpr.upload(file, extName);
            return AjaxResult.me().setResultObj(filePath);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("文件上传失败！");
        }
    }
    //文件上传
    @RequestMapping("/upload")
    public AjaxResult upload(MultipartFile file){
        try {
            String extension = FilenameUtils.getExtension(file.getOriginalFilename());
            String filePath = FastDfsApiOpr.upload(file.getBytes(), extension);
            return AjaxResult.me().setResultObj(filePath);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("文件上传失败！");
        }
    }
    //文件下载
    @RequestMapping("/download")
    public byte[] download(@RequestParam("path")String path){
        try {
            //截取filaName
            path = path.startsWith("/")?path.substring(1):path;
            int index = path.indexOf("/");
            String groupName = path.substring(0,index);
            String fileName = path.substring(0,index+1);
            return FastDfsApiOpr.download(groupName,fileName);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
